package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.HashMap;

@RestController
@RequestMapping("images")
public class ImagesController {

    @Autowired
    ServletContext servletContext;

    @RequestMapping(method = RequestMethod.POST)
    public Object upload(MultipartFile upload) {
        HashMap map = new HashMap();
        try {
            //获取指定文件夹upload的真实路径(绝对路径)
            String realPath = servletContext.getRealPath("/upload");
            //获取图片的路径 /upload/xxxx.jpg
            String imgUrl = UploadUtil.upload(upload, realPath);
            map.put("uploaded", 1);
            map.put("url", imgUrl);
        } catch (Exception e) {
            e.printStackTrace();
            HashMap errorMap = new HashMap();
            errorMap.put("message", e.getMessage());
            map.put("error", errorMap);
        }
        return map;
    }
}
